当前位置:首页 > Python教程 > python进阶

Python 将列表中的头尾两个元素对调

python 将列表中的头尾两个元素对调

定义一个列表,并将列表中的头尾两个元素对调。

例如:

对调前 : [1, 2, 3]
对调后 : [3, 2, 1]

实例 1

def swaplist(newlist):
    size = len(newlist)
     
    temp = newlist[0]
    newlist[0] = newlist[size - 1]
    newlist[size - 1] = temp
     
    return newlist

newlist = [1, 2, 3]
 
print(swaplist(newlist))

以上实例输出结果为:

[3, 2, 1]

实例 2

def swaplist(newlist):
     
    newlist[0], newlist[-1] = newlist[-1], newlist[0]
 
    return newlist
     
newlist = [1, 2, 3]
print(swaplist(newlist))

以上实例输出结果为:

[3, 2, 1]

实例 3

def swaplist(list):
     
    get = list[-1], list[0]
     
    list[0], list[-1] = get
     
    return list
     
newlist = [1, 2, 3]
print(swaplist(newlist))

以上实例输出结果为:

[3, 2, 1]

document 对象参考手册 python3 实例


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!